package com.itheima.travel.controller;

import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.itheima.travel.service.OrderService;
import com.itheima.travel.utils.PayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/pay")
public class PayController {

    @Autowired
    private OrderService orderService;

    @RequestMapping("createUrl")
    public String createUrl(String oid,String total){
        String payUrl = PayUtils.createOrder(oid, 1);
        return payUrl;
    }

    @RequestMapping(path = "/payNotify",produces = "application/xml;charset=utf-8")
    public Map<String,String> payNotify(HttpServletRequest request){
        Map<String,String> resultMap=new HashMap<>();
        try {
            //1.获取微信支付系统传递过来的xml数据输入流
            InputStream inputStream = request.getInputStream();

            //2.将xml输入流转换为Map集合对象
            XmlMapper xmlMapper = new XmlMapper();
            Map<String,String> map = xmlMapper.readValue(inputStream, Map.class);

            //3.调用业务方法处理结果更新订单状态
            orderService.updateState(map);

            //4.处理成功返回数据
            resultMap.put("return_code","SUCCESS");
            resultMap.put("return_msg","OK");
        } catch (IOException e) {
            e.printStackTrace();
            resultMap.put("return_code","FAIL");
            resultMap.put("return_msg",e.getMessage());
        }
        return resultMap;
    }

    @RequestMapping("/findStatus")
    public boolean findStatus(String oid){
        return orderService.isPay(oid);
    }
}
